﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Odyssey.Linq;
using SunTzu.Core.Data;
using SunTzu.Web;
using SunTzu.Utility;
using Odyssey.Web.Models;

namespace Odyssey.Web.Controllers
{
    public class FrontBaseController : Controller
    {
        protected OdysseyDataContext db
        {
            get { return DataContextManager.GetContext(); }
        }

        protected IQueryable<T> GetTable<T>() where T : class, IEntity, new()
        {
            return db.GetTable<T>();
        }

        public tb_account CurrentUser
        {
            get
            {
                var user = Session[WebConstants.CurrentUser] as tb_account;
                return user ?? new tb_account();
            }
            private set
            {
                Session[WebConstants.CurrentUser] = value;
            }
        }

        public bool IsLogin
        {
            get { return CurrentUser.Id > 0; }
        }


        protected void BindTopNavigation()
        {
            ViewData.Add("TopNavigation", GetTable<tb_top_navigation>().ToList());
        }
        protected void BindMasterViewData(int? id)
        {
            BindTopNavigation();
            ViewData.Add("LeftNavigation", GetTable<tb_left_navigation>().Where(item => item.parent == 0 && item.classid == (id ?? 0)).OrderBy(item => item.DisplayOrder).ToList());
            ViewData.Add("SubLeftNavigation", GetTable<tb_left_navigation>().Where(item => item.parent != 0).OrderBy(item => item.DisplayOrder).ToList());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual JsonResult Setlang(string id)
        {
            DefaultCultureInfoProvider.CurrentCulture = id.Trim().ToLower();
            var returnResult = new ReturnResult()
                {
                    //message = "Ok！",
                    action = ReturnResultFactory.Reload,
                    forwordUrl = ""
                };
            return returnResult.ToJsonResult();
        }

        public void SetMessage(string message)
        {
            TempData["message"] = message;
        }

        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            DataContextManager.Clear();
            base.OnResultExecuted(filterContext);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.IsLogin = IsLogin;

            CheckAuthorization(filterContext);

            var user = Session[WebConstants.CurrentUser] as tb_account ?? new tb_account();
        }

        #region Authoriztion

        /// <summary>
        /// 检查登录权限
        /// </summary>
        /// <param name="filterContext"></param>
        private void CheckAuthorization(ActionExecutingContext filterContext)
        {
            LoginAttribute[] actionLoginAttributes = (LoginAttribute[])filterContext.ActionDescriptor.GetCustomAttributes(typeof(LoginAttribute), false);
            LoginAttribute[] controllerLoginAttributes = (LoginAttribute[])filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(LoginAttribute), false);
            bool isLoginRequired = CheckIsLoginRequired(actionLoginAttributes, controllerLoginAttributes);
            if (isLoginRequired)
            {
                // 要求登录
                if (!IsLogin)
                {
                    if (IsAjax())
                    {
                        filterContext.Result = ReturnResultFactory.SessionTimeOut.ToJsonResult();
                    }
                    else
                    {
                        Response.Redirect("/Home/Login?returnUrl=" + Request.RawUrl);
                    }
                }
            }
        }

        /// <summary>
        /// 检查是否需要登录
        /// </summary>
        /// <param name="loginAttributes"></param>
        /// <returns></returns>
        private bool CheckIsLoginRequired(LoginAttribute[] actionLoginAttributes, LoginAttribute[] controllerAttributes)
        {
            if (actionLoginAttributes != null && actionLoginAttributes.Length > 0)
            {
                return actionLoginAttributes[0].IsRequired;
            }
            if (controllerAttributes != null && controllerAttributes.Length > 0)
            {
                return controllerAttributes[0].IsRequired;
            }
            return false;
        }

        /// <summary>
        /// 检查角色Id
        /// </summary>
        /// <param name="loginAttributes"></param>
        /// <returns></returns>
        private int CheckRoleId(LoginAttribute[] loginAttributes)
        {
            if (loginAttributes != null && loginAttributes.Length > 0)
            {
                return loginAttributes[0].RoleId;
            }
            return 0;
        }

        private bool IsAjax()
        {
            return Request.Headers["ajax"].IsNotNullOrEmpty();
        }
        #endregion
    }
}